package com.dianban.weixin.util;

import com.alibaba.fastjson.JSONObject;
import com.dianban.utils.HttpsUtil;
import com.dianban.utils.http.HttpClient;
import com.dianban.utils.http.HttpMethod;
import com.dianban.utils.http.HttpParamers;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class WechatUtils {
    public static final Logger logger = LoggerFactory.getLogger(WechatUtils.class);
    public static final String PUBLIC_WEIXIN_KEY = "gh_c61217aba99d";
    public static final String APPID = "wx4344bfe685ee932a";
    public static final String SECRET = "587fea4d0967df8c3f4cd927ebf40e11";

    public static String getAccessToken() {
        String accessToken = "";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
        String result = HttpsUtil.callHttps("", url);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject != null) {
                accessToken = String.valueOf(jsonObject.get("access_token"));
            }
        }
        return accessToken;
    }

    public static final String WAIT_PAY_TEMPLATE_ID = "Q1ZpW_Y9DxnyGKceDv85TT8rJZ0brNfvgm4Y94kQJso";
    public static final String PAY_SUCCESS_TEMPLATE_ID = "M6CEMrMK2sBrolt1PE2FExdaN3WNMkmtV0jYnVtNkq8";

    // 发送订阅消息（待支付订单）
    // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
    public static JSONObject wait_pay(String touserOpenid, String orderNo, String createTime, String amount, String desc) {
        JSONObject jsonObject = new JSONObject();
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isNotBlank(accessToken)) {
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
                HttpParamers httpParamers = new HttpParamers(HttpMethod.POST);
                httpParamers.addParam("touser", touserOpenid);
                httpParamers.addParam("template_id", WAIT_PAY_TEMPLATE_ID);
                httpParamers.addParam("page", "pages/unpayOrder/index");
                //订单编号
                //{{character_string1.DATA}}
                //下单时间
                //{{time2.DATA}}
                //支付金额
                //{{amount4.DATA}}
                //备注
                //{{thing6.DATA}}
                if (desc.length() >= 17) {
                    desc = desc.substring(0, 15) + "...";
                }
                Map<String, Map<String, Object>> data = new HashMap<>();
                Map<String, Object> thing1Map = new HashMap<>();
                thing1Map.put("value", orderNo);
                data.put("character_string1", thing1Map);
                Map<String, Object> time2Map = new HashMap<>();
                time2Map.put("value", createTime);
                data.put("time2", time2Map);
                Map<String, Object> amount4Map = new HashMap<>();
                amount4Map.put("value", "¥" + amount);
                data.put("amount4", amount4Map);
                Map<String, Object> thing6Map = new HashMap<>();
                thing6Map.put("value", desc);
                data.put("thing6", thing6Map);
                httpParamers.addParam("data", data);

                httpParamers.setJsonParamer();
                String resultService = HttpClient.doService(url, httpParamers, null);
                logger.info("待支付订单提醒:{}", resultService);
                // {
                //   "errcode":0,
                //   "errmsg":"ok",
                //}
                if (StringUtils.isNotBlank(resultService)) {
                    jsonObject = JSONObject.parseObject(resultService);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    // 支付成功提醒
    public static JSONObject pay_success(String touserOpenid, String orderNo, String createTime, String amount) {
        JSONObject jsonObject = new JSONObject();
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isNotBlank(accessToken)) {
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
                HttpParamers httpParamers = new HttpParamers(HttpMethod.POST);
                httpParamers.addParam("touser", touserOpenid);
                httpParamers.addParam("template_id", PAY_SUCCESS_TEMPLATE_ID);
                httpParamers.addParam("page", "pages/index/index");
                //订单号
                //{{character_string1.DATA}}
                //支付金额
                //{{amount3.DATA}}
                //支付时间
                //{{time4.DATA}}
                Map<String, Map<String, Object>> data = new HashMap<>();
                Map<String, Object> thing1Map = new HashMap<>();
                thing1Map.put("value", orderNo);
                data.put("character_string1", thing1Map);
                Map<String, Object> amount3Map = new HashMap<>();
                amount3Map.put("value", "¥" + amount);
                data.put("amount3", amount3Map);
                Map<String, Object> time4Map = new HashMap<>();
                time4Map.put("value", createTime);
                data.put("time4", time4Map);
                httpParamers.addParam("data", data);

                httpParamers.setJsonParamer();
                String resultService = HttpClient.doService(url, httpParamers, null);
                logger.info("支付成功提醒:{}", resultService);
                // {
                //   "errcode":0,
                //   "errmsg":"ok",
                //}
                if (StringUtils.isNotBlank(resultService)) {
                    jsonObject = JSONObject.parseObject(resultService);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    // 获取订阅消息模版列表
    public static JSONObject getTemplateList() {
        JSONObject jsonObject = new JSONObject();
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isNotBlank(accessToken)) {
                String url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + accessToken;
                HttpParamers httpParamers = new HttpParamers(HttpMethod.GET);
                httpParamers.setJsonParamer();
                String resultService = HttpClient.doService(url, httpParamers, null);
                if (StringUtils.isNotBlank(resultService)) {
                    jsonObject = JSONObject.parseObject(resultService);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

}
